var BackendInterface = function(){
	var _self = this;

	_self.newItem = false;
	_self.editing = false;
	_self.tableToEdit = {};
	_self.rowToEdit = {};
	_self.refreshTbl = {};
	_self.backendRequest = 0;

	_self.searchItems = [];

	_self.getData = function(url, params, callback){
		$.getJSON( url, params )
			.done(function( result ) {
				if(result.error != undefined){
					$(".status-message").html("Error: " + result.error);
					$("body").css('cursor', 'default');
					if(result.error == "401 Unauthorized"){
						$("#currentUser").text("User: No User");
						document.location.href = "#00";
					}
					return;
				}
				else{
					$(".status-message").html("OK");
					if(callback){
						callback(result);
					};
				}
			})
			.fail(function( jqxhr, textStatus, error ) {
				var err = textStatus + ", " + error;
				console.log( err );
			});
	};
	_self.writeData = function(url, params, callback){
		$.get( url, params )
			.done(function( result ) {
				if(result.error != undefined){
					$(".status-message").html("Error: " + result.error);
					$("body").css('cursor', 'default');
					return;
				}
				else{
					$(".status-message").html("OK");
					if(callback){
						callback(result);
					};
				}
			})
			.fail(function( jqxhr, textStatus, error ) {
				var err = textStatus + ", " + error;
				console.log( err );
			});
	};


	_self.editItem = function(editTable, editRow, refreshTableFunction, request){
		if(_self.editing == false){
			_self.backendRequest = request;
			_self.tableToEdit = editTable;
			_self.rowToEdit = editRow;
			_self.refreshTbl = refreshTableFunction;

			_self.makeRowEditable(_self.tableToEdit, _self.rowToEdit);
			_self.editing = true;
		}
	};
	_self.addItem = function(editTable, refreshTableFunction, request){
		if(_self.newItem != true){
			_self.backendRequest = request;

			var sampleRow = $(editTable).children()[0];

			$(editTable).prepend(sampleRow.outerHTML);

			var newRow = $(editTable).children()[0];

			$($(newRow).children()).each(function(index,value){
				$(newRow).children()[parseInt(index)].innerHTML = "InsertValue";
			});
			_self.newItem = true;
			_self.editItem(editTable, $(newRow), refreshTableFunction, request);
		}
	};
	_self.cancel = function(request){
		if(request == _self.backendRequest){
			_self.backendRequest = 0;
			_self.editing = false;
			_self.newItem = false;
			_self.tableToEdit = {};
			_self.rowToEdit = {};

			_self.searchItems = [];
			_self.refreshTbl();
		}
	};
	_self.deleteItem = function(request){
		if(_self.newItem == false && _self.editing == true && request == _self.backendRequest){
			_self.deleteBackendItem(request);
		}
	};


	_self.makeRowEditable = function(table, row){
		_self.searchItems = [];
		var params = {};

		$(table.children()).removeClass("selected");

        $(row).addClass("selected");

        var random = Math.random();
        var url = "js/tableParams/" + _self.backendRequest + ".json?x=" + random;

        $.get(url, function(tableParams) {
	        $(row.children()).each(function(index,value){

	        	var fieldDefinition = $(this);
	        	var rowClass = $(this).attr('class');
	        	var rowValue = value.innerHTML;

	        	if(tableParams.desc[parseInt(index)].refReq == undefined){
	        		_self.searchItems[parseInt(index)] = $(value).html();

					fieldDefinition.replaceWith("<input class='" + rowClass + "' type='text' value='" + rowValue + "'></input>");
				}
				else{
					var refReq 				= tableParams.desc[parseInt(index)].refReq;
					var refFields 			= tableParams.desc[parseInt(index)].refFields;
					var fieldName 			= tableParams.desc[parseInt(index)].param;

		            $.getJSON(window.CONSTANTS.SERVICE_URL, {
			                request: refReq,
			                action: 'getItems'
			            },
			            function(response) {
			            	var content = "";
			            	var caption = "";

			            	var caption = "<div class='droe-select " + rowClass + "'><div class='caption'>" + rowValue + "<i class='caret'></i></div>";

							content = "<div class='content'><div class='clearfix tbl'>";

			                $.each(response, function(index, value) { 			// trought rows
			                	$.each(value,function(index,value){ 			// trought columns
			                		var indx = index;
			                		var val = value;
			                		$(refFields).each(function(index,value){	// trougth ref
			                			if(indx === value.field){
			                				if(value.field === "ID"){
			                					content = content + "<div class='clearfix row data' data-x='"+val+"'>";
			                				}
			                				else{
			                					content = content + "<div class='col w"+value.width+"'>"+val+"</div>";
			                				}
			                			}
			                		});
			                	});
			                	content = content + "</div>";
			                });

			                content = content + "</div></div>";//closed div tbl and then div content 

			                fieldDefinition.replaceWith(caption + content + "</div>");

                            $(".droe-select .caption").click(function(e){
				                e.stopPropagation();
				                var x = $(this).parent();
				                x.find(".content").toggle(100);
				            });
				            $(".droe-select .row").click(function(){
				                var caption = $(this).closest(".droe-select").find('.caption');
				                caption.attr("data-id", $(this).data("x"));
				                caption.html($(this).text() + "<i class='caret'></i>");
				            });
				            $(document).click(function(e){
				                $(".droe-select .content").hide();
				            });
		            });					
				}
	        });
        });
	};
	_self.save = function(request){
		if(_self.newItem == true && _self.editing == true && _self.backendRequest == request){
			_self.addBackendItem(request);
		}
		else if(_self.newItem == false && _self.editing == true && _self.backendRequest == request){
			_self.updateBackendItem(request);
		}
	};
	_self.addBackendItem = function(request){
        var params = {};
        var tableParams = {};
        var hasID = false;
    	params.request = _self.backendRequest;
    	params.action = "addItems";

        var random = Math.random();
        var url = "js/tableParams/" + params.request + ".json?x=" + random;

        $.get(url, function(tableParams) {
        	$(_self.rowToEdit.children()).each(function(index,value){
        		if(tableParams.desc[index].param == "ID" && hasID == false)
        			hasID = true;

        		if(hasID == true)
        			index = index + 1;

        		if($(value).hasClass("droe-select")){
        			params[tableParams.desc[index].originFieldName] = $(value).find(".caption").data("id");
        		}
        		else{
        			params[tableParams.desc[index].param] = $(value).val();
        		}
        	});
	        _self.writeData(window.CONSTANTS.SERVICE_URL, params, function(responce){
	        	_self.cancel(request);
        	});
        });
	};
	_self.updateBackendItem = function(request){
        var params = {};
        var tableParams = {};
        var hasID = false;
        var indexID = 0;
    	params.request = _self.backendRequest;
    	params.action = "updateItems";

        var random = Math.random();
        var url = "js/tableParams/" + params.request + ".json?x=" + random;

        $.get(url, function(tableParams) {
        	$(_self.rowToEdit.children()).each(function(index,value){
        		if(tableParams.desc[index].param == "ID" && hasID == false)
        			hasID = true;

        		if(hasID == true)
        			indexID = index + 1;
        		else
        			indexID = index;

        		if($(value).hasClass("droe-select")){    			
	        		params[tableParams.desc[indexID].originFieldName] = $(value).find(".caption").data("id");
        			params["find_"+tableParams.desc[indexID].originFieldName] = _self.searchItems[index];
        		}
        		else{
	        		params[tableParams.desc[indexID].param] = $(value).val();
        			params["find_"+tableParams.desc[indexID].param] = _self.searchItems[index];
        		}
        	});
	        _self.writeData(window.CONSTANTS.SERVICE_URL, params, function(responce){
	        	_self.cancel(request);
        	});
        });
	};
	_self.deleteBackendItem = function(request){
        var params = {};
        var tableParams = {};
        var hasID = false;
    	params.request = _self.backendRequest;
    	params.action = "deleteItems";

    	var random = Math.random();
        var url = "js/tableParams/" + params.request + ".json?x=" + random;

        $.get(url, function(tableParams) {
	    	$(_self.searchItems).each(function(index,value){
        		if(tableParams.desc[index].param == "ID" && hasID == false)
        			hasID = true;

        		if(hasID == true)
        			index = index + 1;

        		if(tableParams.desc[index].originalFieldName)
	    			params[tableParams.desc[index].originFieldName] = value;
	    		else
	    			params[tableParams.desc[index].param] = value;
	    	});
	        _self.writeData(window.CONSTANTS.SERVICE_URL, params, function(responce){
	        	_self.cancel(request);
        	});
	    });
	};
};